package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response){
        //校验参数
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("请输入用户名");
        }
        if(StringUtils.isEmpty(password)){
            throw new RuntimeException("请输入密码");
        }
        //申请令牌 authToken
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //将jti的值存入cookie中
        this.saveJtiToCookie(authToken.getJti(),response);

        //返回结果
        return new Result(true, StatusCode.OK,"登录成功",authToken.getJti());
    }

    /**
     * 将令牌的短标识存入cookie
     * @param jti
     * @param response
     */
    private void saveJtiToCookie(String jti, HttpServletResponse response) {

        /**
         * 通过工具类存入
         * 参数1:response对象
         * 参数2:cookie域名
         * 参数3:cookie路径
         * 参数4:cookie名称
         * 参数5:cookie值
         * 参数6:cookie的有效期 -1(浏览器关闭销毁)
         * 参数7:HttpOnly:客户端是否访问
         */
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }

    /**
     * 登录页面跳转
     * 静态资源和登录方法需要放行
     */
    @RequestMapping("/toLogin")
    //接收参数,网关传过来的访问全路径地址,required值为true则表示该参数必须有,false表不一定携带
    public String toLogin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model){
        //将路径地址带回到登录页面
        model.addAttribute("from",from);
        return "login";
    }
}
